package com.mikufufu.blog.controller.api;

import com.mikufufu.blog.common.entity.AjaxResult;
import com.mikufufu.blog.model.entity.Archives;
import com.mikufufu.blog.model.vo.api.ArchivesVO;
import com.mikufufu.blog.service.ArchivesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "归档")
@RestController
@RequestMapping("/archives")
public class ArchivesController {

    @Autowired
    private ArchivesService archivesService;

    @GetMapping("/list")
    @ApiOperation("通过主键获取信息")
    public AjaxResult<List<ArchivesVO>> list() {
        List<ArchivesVO> archives = new ArrayList<>();
        List<Archives> list = archivesService.list();
        Map<String, List<Archives>> groupByYear = list.stream().collect(Collectors.groupingBy(item -> String.valueOf(item.getPublishDate().getYear())));
        for (Map.Entry<String, List<Archives>> entry : groupByYear.entrySet()) {
            ArchivesVO archivesVO = new ArchivesVO();
            archivesVO.setYear(entry.getKey());
            archivesVO.setArchives(entry.getValue());
            archivesVO.setTotal(entry.getValue().size());
            archives.add(archivesVO);
        }
        return AjaxResult.data(archives.stream().sorted(Comparator.comparing(ArchivesVO::getYear).reversed()).collect(Collectors.toList()));
    }

}
